package com.pengpeng.jjwt.config;

import com.pengpeng.jjwt.annotation.JwtIgnore;
import com.pengpeng.jjwt.common.exception.CustomException;
import com.pengpeng.jjwt.common.result.ResultCode;
import com.pengpeng.jjwt.constants.JwtConstant;
import com.pengpeng.jjwt.entity.JwtParam;
import com.pengpeng.jjwt.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author pengp
 * @date 2022年03月03日 16:06
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtParam jwtParam;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("-----preHandle");

        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            JwtIgnore jwtIgnore = handlerMethod.getMethodAnnotation(JwtIgnore.class);
            if(jwtIgnore != null){
                return true;
            }
        }

        if (HttpMethod.OPTIONS.equals(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        final String authHeader = request.getHeader(JwtConstant.AUTH_HEADER_KEY);

        if(StringUtils.isEmpty(authHeader)){
            log.info("====用户未登录请先登录===");
            throw new CustomException(ResultCode.USER_NOT_LOGGED_IN);
        }

        if(!JwtUtils.validate(authHeader)){
            log.info("======token格式异常============");
            return false;
        }

        final String authToken = JwtUtils.getRawToken(authHeader);
        Claims claims = JwtUtils.parseToken(authToken,jwtParam.getBase64Secret());
        if(claims == null){
            log.info("=======token解析异常========");
            return false;
        }
        request.setAttribute("CLAIMS",claims);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
